#include "ParseJPG.h"

int parse_jpg(char*filePath,struct Meta* ret_m){

	FILE* fp;
	int i;
	unsigned char Starter[2];
	unsigned char FrameHeader[2];
	unsigned char FrameSize[2];
	
	unsigned char WIDTH[2];
	unsigned char HEIGHT[2];
	int Length=0;

	int W=0;
	int H=0;

	
	long OFFSET=0;




	fp = fopen(filePath,"rb");

	ret_m->fileSize = GetFileLength(fp);	

	ret_m->upnpClass=(char*)malloc(strlen(UPNP_PICTURE)+1);
	strcpy(ret_m->upnpClass,UPNP_PICTURE);

	



	i = 0;
	fread(Starter,sizeof(unsigned char),(size_t)2,fp);
	OFFSET +=2;

		
	while(i++ < 100)
	{
		fread(FrameHeader,sizeof(unsigned char),(size_t)2,fp);
		fread(FrameSize,sizeof(unsigned char),(size_t)2,fp);

		OFFSET += 4;

		if(FrameHeader[0] == 0xFF && FrameHeader[1] == 0xC0)
		{
			OFFSET +=1;
			fseek(fp,OFFSET,SEEK_SET);

			fread(HEIGHT,sizeof(unsigned char),(size_t)2,fp);
			fread(WIDTH,sizeof(unsigned char),(size_t)2,fp);

			W = getIntFromByte(WIDTH,2);
			H = getIntFromByte(HEIGHT,2);


			break;
		}
		Length = getIntFromByte(FrameSize,2);
		OFFSET = OFFSET + Length - 2;


		fseek(fp,OFFSET,SEEK_SET);
	}


	ret_m->ResolutionX=W;
	ret_m->ResolutionY=H;

	if(W <=640 && H <=480)
	{
		ret_m->ProtocolInfo = (char*)malloc(strlen(PROTOCOL_JPG_SM)+1);
		strcpy(ret_m->ProtocolInfo,PROTOCOL_JPG_SM);
	}else if(W <=1024 && H <= 768 )
	{
		ret_m->ProtocolInfo = (char*)malloc(strlen(PROTOCOL_JPG_MED)+1);
		strcpy(ret_m->ProtocolInfo,PROTOCOL_JPG_MED);
	}
	else
	{
		ret_m->ProtocolInfo = (char*)malloc(strlen(PROTOCOL_JPG_LRG)+1);
		strcpy(ret_m->ProtocolInfo,PROTOCOL_JPG_LRG);
	}


	fclose(fp);
	return FILE_PICTURE;

}